//
//  DetailSubVC.m
//  New_Runway
//
//  Created by mack on 2018/2/8.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "DetailSubVC.h"
#import "NRWCarCarListCell.h"
#import "CarDetailMainVC.h"
#import "NRWCarListsModel.h"
#import "DataCrmdetailModel.h"
#import "DataCrmDetailCell.h"
#import "CRMCustomerDetailVC.h"

@interface DetailSubVC ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong) UITableView *tableview;
@property (assign, nonatomic) NSInteger pageNo;
@property (nonatomic, strong) NSMutableArray *carArray;
@property (nonatomic, strong) NSMutableArray *crmDetailList;
@end

@implementation DetailSubVC
-(NSMutableArray *)carArray{
    
    if (!_carArray) {
        _carArray = [[NSMutableArray alloc] init];
    }
    return _carArray;
}
-(NSMutableArray *)crmDetailList{
    if (!_crmDetailList) {
        _crmDetailList = [[NSMutableArray alloc] init];
    }
    return _crmDetailList;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBarView.hidden = YES;
    self.view.backgroundColor = kColorBlue();
    [self initTableview];
    self.pageNo = 1;
    if (self.isSale == YES) {
        [self loadCrmDataDatail];
    }else{
        [self loadCarList];
    }
}
-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    _tableview.estimatedRowHeight = 0;
    _tableview.estimatedSectionHeaderHeight = 0;
    _tableview.estimatedSectionFooterHeight = 0;
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    self.tableview.backgroundColor = MAIN_COLOR();
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableview registerNib:[UINib nibWithNibName:@"NRWCarCarListCell" bundle:nil] forCellReuseIdentifier:@"NRWCarCarListCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"DataCrmDetailCell" bundle:nil] forCellReuseIdentifier:@"DataCrmDetailCell"];
    self.tableview.mj_header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downPullRefresh)];
    self.tableview.mj_footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upPullLoadMore)];
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view);
        make.left.right.equalTo(weakSelf.view);
    }];
    
    
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isSale == YES) {
        return 70;
    }
    return 110;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.isSale == YES) {
        return self.crmDetailList.count;
    }
    return self.carArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isSale == YES) {
        DataCrmDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DataCrmDetailCell"];
        dataDetailResult *result = self.crmDetailList[indexPath.row];
        cell.result = result;
        return cell;
    }
    NRWCarCarListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NRWCarCarListCell"];
    cell.carModel = self.carArray[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.isSale == YES) {
        
        CRMCustomerDetailVC *vc = [CRMCustomerDetailVC new];
        dataDetailResult *info = self.crmDetailList[indexPath.row];
        vc.customerName = info.customerName;
        vc.customerShopId = info.customerShopId;
        vc.isDataPush = YES;
//        vc.customerId = info.customerInfo.customerId;
//        vc.followState = info.customerInfo.followState;
//        vc.cityId = info.customerInfo.customer.cityId;
//        vc.provinceId = info.customerInfo.customer.provinceId;
//        vc.levelId = info.customerInfo.levelId ;
//        vc.channelId = info.customerInfo.channelId;
        [self.navigationController pushViewController:vc animated:YES];
    
    }else{
    
        CarDetailMainVC *carDVC = [[CarDetailMainVC alloc] init];
        carDVC.isShowR = YES;
        Result *rt = self.carArray[indexPath.row];
        carDVC.carID = rt.carId;
        carDVC.modelID = rt.modelId;
        [self.navigationController pushViewController:carDVC animated:YES];
    }
    
}
-(void)downPullRefresh{
    self.pageNo = 1;
    if (self.isSale == YES) {
        [self loadCrmDataDatail];
    }else{
        [self loadCarList];
    }
}
-(void)upPullLoadMore{
    self.pageNo += 1;
    if (self.isSale == YES) {
        [self loadCrmDataDatail];
    }else{
        [self loadCarList];
    }}

-(void)loadCarList{
    NSDictionary *params;

    if (self.isDay == YES) {
        
        params =@{
                  @"pageSize":@(15),
                  @"pageIndex":@(self.pageNo),
                  @"marketId":[NRWCarUser sharedUser].marketId,
                  @"startDate":[NRWCarTurnTime timestampSwitchTime:self.currentTime andFormatter:@"yyyy-MM-dd"],
                  @"shopId":self.shopID,
                  @"statisType":self.statisType,
                  @"endDate":[NRWCarTurnTime timestampSwitchTime:(self.currentTime+86400 * 1000) andFormatter:@"yyyy-MM-dd"],
                  };
    }else{
        
        params =@{
                 @"marketId":[NRWCarUser sharedUser].marketId,
                 @"startDate":[NRWCarTurnTime timestampSwitchTime:self.currentTime andFormatter:@"yyyy-MM-dd"],
                 @"shopId":self.shopID,
                 @"statisType":self.statisType,
                 @"endDate":[self nextMonth:[NRWCarTurnTime timestampSwitchTime:self.currentTime andFormatter:@"yyyy-MM-dd"]],
                 };
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,carStateApi];
    [YQNetworking postWithUrl:url refreshRequest:YES cache:YES params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        NRWCarListsModel *carModel = [NRWCarListsModel mj_objectWithKeyValues:response];
        if (self.pageNo == 1) {
            [self.carArray removeAllObjects];
        }
        if (carModel.code == 1) {
            for (NSDictionary *dic  in carModel.result) {
                Result *rt = [Result mj_objectWithKeyValues:dic];
                [self.carArray addObject:rt];
            }
        }
        [self.tableview reloadData];
        [self endRefresh];
    } failBlock:^(NSError *error) {
        [self endRefresh];
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
    
}
-(void)loadCrmDataDatail{
    NSString *url = [NSString stringWithFormat:@"%@%@",CRMContextApi,DataCrmDetailApi];
    NSDictionary *params = @{
                             @"followState":@(self.followState),
                             @"queryDate":[NRWCarTurnTime timestampSwitchTime:self.currentTime andFormatter:@"yyyy-MM-dd"],
                             @"searchType":self.searchType,
                             @"shopId":self.shopID,
                             @"pageSize":@(10),
                             @"pageIndex":@(self.pageNo),
                             };
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        DataCrmdetailModel *model = [DataCrmdetailModel mj_objectWithKeyValues:response];
        if (self.pageNo == 1) {
            [self.crmDetailList removeAllObjects];
        }
        if (model.code == 1) {
            for (NSDictionary *dic  in model.result) {
                dataDetailResult *result = [dataDetailResult mj_objectWithKeyValues:dic];
                [self.crmDetailList addObject:result];
            }
            [self.tableview reloadData];
        }
        [self endRefresh];

    } failBlock:^(NSError *error) {
        [self endRefresh];
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
    
    
}
-(NSString *)nextMonth:(NSString *)date{
    NSString *dateStr;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone localTimeZone];
    [formatter setDateFormat :@"yyyy-MM-dd"];
    [formatter setTimeZone:timeZone];
    NSDate *dateTime = [formatter dateFromString:date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    // 指定获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    // 获取不同时间字段的信息
    NSDateComponents* comp = [gregorian components: unitFlags fromDate:dateTime];
    if (comp.month == 12) {
        dateStr = [NSString stringWithFormat:@"%ld-01-01",comp.year+1];

    }else{
        dateStr = [NSString stringWithFormat:@"%ld-%ld-01",comp.year,comp.month + 1];
    }
    return dateStr;
}
-(void)endRefresh{
    [self.tableview.mj_header endRefreshing];
    [self.tableview.mj_footer endRefreshing];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
